package app.controllers;

import app.Const;
import app.kit.TypeKit;
import app.models.basic.Dict;
import app.models.member.RiskRule;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.primitives.Ints;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.ext.interceptor.POST;
import goja.mvc.Controller;
import goja.rapid.datatables.DTCriterias;

import java.util.List;

/**
 * <p>
 * 产品风险购买用户评级匹配规则维护
 * </p>
 *
 * @author liuhui
 * @version 1.0
 * @since JDK 1.6
 */
public class RiskruleController extends Controller{
    /**
     * The index route.
     */
    @Before(GET.class)
    public void index() {
    }

    public void dtlist(){
        final DTCriterias criterias = DTCriterias.criteriasWithRequest(getRequest());
        renderDataTables(criterias, "riskrule");
    }

    @Before(GET.class)
    public void edit() {
        String id = getPara(0, "0");
        RiskRule rule = RiskRule.dao.findById(id);
        if(null != rule){
            List<Dict> dicts = Dict.dao.risk_tolerance();
            for (Dict dict : dicts) {
                String  code = dict.getStr("code");
                if(Strings.isNullOrEmpty(code)){
                    continue;
                }
                if(Ints.tryParse(code) == TypeKit.getInt(rule, "risk_tolerance")){
                    rule.put("risk_tolerance_name", dict.getStr("name"));
                    break;
                }
            }
        }

        setAttr(Const.ACTION_ATTR, Const.EDIT_ACTION);
        setAttr("rule", rule);
        setAttr("risk_level", Dict.dao.risk_level());
        render("item.ftl");
    }

    @Before(POST.class)
    public void save() {
        RiskRule rule = getModel(RiskRule.class,"rule");
        String[] risk_levels = getParaValues("risk_level");

        String levelStr = Joiner.on(",").join(risk_levels);
        rule.set("risk_level",levelStr);

        //选择次数
        if(rule.getStr("type").equals("1")){
            rule.set("amount",0);
        }else {
            rule.set("deal",0);
        }

        rule.update();
       redirect("/riskrule");
    }

}
